﻿using B.S.BaseData.suyuan.ApiWrite.Account.Command;
using B.S.BaseData.Suyuan.Command;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.BaseData.suyuan.ApiWrite.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class traceabilityController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IWebHostEnvironment _env;
        public traceabilityController(IMediator mediator, IWebHostEnvironment env)
        {
            this.mediator = mediator;
            _env = env;
        }

        /// <summary>
        /// 添加基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResult<object>> Addtraceability(AddtraceabilityCommand request, CancellationToken cancellationToken)
        {
           return mediator.Send(request);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult unload(IFormFile file) 
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return BadRequest("请选择要上传的图片");
                }

                // 检查文件类型是否为图片（这里简单示例，可根据实际需求扩展）
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!allowedExtensions.Contains(fileExtension))
                {
                    return BadRequest("仅支持上传.jpg,.jpeg,.png,.gif格式的图片");
                }

                // 检查文件大小（这里示例限制为2MB，可根据需求调整）
                var maxFileSize = 2 * 1024 * 1024; // 2MB
                if (file.Length > maxFileSize)
                {
                    return BadRequest("图片大小不能超过2MB");
                }

                var str = Guid.NewGuid();
                // 使用IWebHostEnvironment获取内容根目录
                var imgFolderPath = Path.Combine(_env.ContentRootPath, "img");
                if (!Directory.Exists(imgFolderPath))
                {
                    Directory.CreateDirectory(imgFolderPath);
                }
                var p = Path.Combine(imgFolderPath, str + file.FileName);
                using (var stream = new FileStream(p, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // 返回标准的成功响应，包含图片的访问路径
                return Ok(new
                {
                    statusCode = 200,
                    message = "图片上传成功",
                    data = $"https://localhost:7106/img/{str + file.FileName}"
                });
            }
            catch (Exception ex)
            {
                // 记录日志（这里可根据实际需求集成日志框架）
                System.Console.WriteLine($"图片上传失败: {ex.Message}");
                return StatusCode(500, "图片上传失败，请联系管理员");
            }
        }
        /// <summary>
        /// 删除基本信息1111
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpDelete]
        public Task<ApiResult<object>> Delete(DeleteCommand request, CancellationToken cancellationToken)
        {
            return mediator.Send(request);
        }
    }
}
